package com.niodata.dp.mybatis;

import com.niodata.dp.collection.WrappedStringKeyMap;
import com.niodata.dp.util.JsonUtil;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class WrappedStringKeyMapTypeHandler extends BaseTypeHandler<WrappedStringKeyMap>
      implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGNVARCHAR;
  }

  @Override
  public Class getTypeHandlerClass() {
    return WrappedStringKeyMapTypeHandler.class;
  }

  @Override
  public Class getJavaClass() {
    return WrappedStringKeyMap.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement preparedStatement, int i,
        WrappedStringKeyMap wrappedStringKeyMap, JdbcType jdbcType) throws SQLException {
    String json = null;
    try {
      json = JsonUtil.toJson(wrappedStringKeyMap);
    } catch (Exception ex) {
      //
    }
    preparedStatement.setString(i, json);
  }

  @Override
  public WrappedStringKeyMap getNullableResult(ResultSet resultSet, String s) throws SQLException {
    WrappedStringKeyMap map = null;
    String str = resultSet.getString(s);
    if (str == null) {
      return null;
    }
    try {
      map = JsonUtil.fromJson(WrappedStringKeyMap.class, str);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return map;
  }

  @Override
  public WrappedStringKeyMap getNullableResult(ResultSet resultSet, int i) throws SQLException {
    WrappedStringKeyMap map = null;
    String str = resultSet.getString(i);
    if (str == null) {
      return null;
    }
    try {
      map = JsonUtil.fromJson(WrappedStringKeyMap.class, str);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return map;
  }

  @Override
  public WrappedStringKeyMap getNullableResult(CallableStatement callableStatement, int i)
        throws SQLException {
    return null;
  }
}
